package org.yinxue.swing.core.action;


import fun.codedesign.yinxue.util.EnvUtil;
import fun.codedesign.yinxue.util.StringUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class DirChooserActionListener implements ActionListener {

    static final String TEXT_PROJECT = "text_project";

    public String filePath;

    ActionListener actionListener;

    JFileChooser chooser;

    public DirChooserActionListener() {
        filePath = EnvUtil.getProperty(TEXT_PROJECT, System.getProperty("user.dir"));
        chooser = new JFileChooser(filePath);
        chooser.setPreferredSize(new Dimension(800, 600));
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        chooser.setMultiSelectionEnabled(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        int open = chooser.showOpenDialog(null);
        if (JFileChooser.APPROVE_OPTION == open) {
            filePath = chooser.getSelectedFile().getAbsolutePath();
            String oldFilePath = EnvUtil.getProperty("dirs");
            if (StringUtil.isNotEmpty(oldFilePath) && !oldFilePath.contains(filePath)) {
                // TODO 统一key， 追加已打开的文件
                EnvUtil.setProperty("dirs", filePath + ";" + oldFilePath);
            } else {
                EnvUtil.setProperty("dirs", filePath);
            }
//            EnvUtil.setProperty(TEXT_PROJECT, filePath);
//            jText_inputpath.setText(filePath);
            if (actionListener != null) {
                actionListener.actionPerformed(null);
            }
        } else {
            // doNoting
        }
    }

    public void addYxValueChange(ActionListener actionListener) {
        this.actionListener = actionListener;
    }
}
